<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Car;
use App\Models\User;
use App\Models\Order;
use Session;

class IndexController extends Controller
{
    public function index(Request $request)
    {
    	$list = Car::paginate(20);
    	return view('sharecar.index',compact('list'));
    }

    public function reg(Request $request)
    {
    	return view('sharecar.register');
    }

    public function regSave(Request $request)
    {
    	$rs['status'] = 'danger';
    	$rs['msg']    = 'failed';
        
    	$data = $request->except(['_token','car_id']);
    	$flag = User::create($data);
    	if($flag) {
            session(['user' => $flag]);
    		$rs['status'] = 'success';
    		$rs['msg']    = 'success';
            return redirect('order-create');

    	}
    	return back()->with('rs',$rs);
    }

    public function login(Request $request)
    {
    	return view('sharecar.login');
    }

    public function loginDo(Request $request)
    {
        $email    = trim($request->email);
        $password = trim($request->password);
        $user = User::where(['email'=>$email])->first();
        //dd($user);
        if(object_get($user,'password') == $password) {
            session(['user' => $user]);
            if(session('car_id')) {
                return redirect('order-create');    
            } else {
                return redirect('/');
            }
            
        } 
        $rs['status'] = 'danger';
        $rs['msg']    = 'Login failed';
        return back()->with('rs',$rs);
    }

    public function book(Request $request)
    {
    	if(!session('user')) {
    		return redirect('login');
    	}
    }

    public function logout(Request $request)
    {
        session(['user'=>null]);
        session(['car_id'=>null]);
        return redirect('login');
    }

    public function autoClose()
    {
        $orders = Order::whereNull('picked_at')->get();
       // dd($orders);
        foreach ($orders as $k => $v) {
            
           
            $book_time = strtotime($v->booking_at);
            $now = time(); 
            $mins = round(($now-$book_time)/60) ; 
            if($mins>30) {
                $car = Car::find($v->car_id);
                $car->status = 'available';
                $car->save();
            }
            

        }
    }

    
}
